<?php
declare (strict_types = 1);

namespace app\validate\common\site;

use think\facade\Cache;
use think\Validate;

class SiteValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'account' => ['require'],
        'password' => ['require'],
        'mobile' => ['require', 'mobile'],
        'captcha' => ['require', 'checkCaptcha'],

        'type' => ['require'],
        // 'file' => ['require', 'fileSize:10485760'], // 10M
        'file' => ['require'],
    ];

    protected $field = [
        'account' => '账号',
        'password' => '密码',
        'mobile' => '手机号码',
        'captcha' => '验证码',

        'type' => '文件类型',
        'file' => '文件',
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [];

    /**
     * 场景
     * @var array
     */
    protected $scene = [
        'account' => ['account', 'password'],
        'login' => ['mobile', 'captcha'],
        'send' => ['mobile'],
        'upload' => ['type'],
        'file' => ['file'],
    ];

    /**
     * @param $value
     * @param $rule
     * @param $data
     * @return bool|mixed
     */
    protected function checkCaptcha($value, $rule, $data)
    {
        // 线上检测
        if ('local' == config('app.app_name')) {
            return true;
        }

        // 获取忽略验证码手机号
        $whiteList = explode(',', config('logic.mobile_white_list'));
        if (in_array($data['mobile'], $whiteList)) {
            return true;
        }

        $mobile = $data['mobile'];
        $cacheKey = 'sms_' . $mobile;

        $code = Cache::get($cacheKey);
        if (empty($code)) {
            return lang('app.sms expire');
        }

        if ($value != $code) {
            return lang('app.sms error');
        }

        return true;
    }
}
